package com.csair.platform.cit.service.controller;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.csair.invoice.common.base.util.StringUtil;
import com.csair.invoice.common.base.vo.JsonResult;
import com.csair.platform.cit.service.feignclient.usercenter.UserFeignClient;
import com.csair.platform.usercenter.facade.model.user.UserVo;

/**
 * 接口辅助类
 * @author liaoxiaojin
 *
 */
@Component
public class BaseController {
    
    /**
     * 用户接口客户端
     */
    @Autowired
    private UserFeignClient userFeignClient;


    /**
     * 导出
     * @param response 1
     * @param book 2
     * @param fileName 3
     * @throws IOException 异常
     */
    protected void exportExcel(HttpServletResponse response, Workbook book, String fileName) throws IOException {
        try {
            response.setHeader(HttpHeaders.CONTENT_TYPE, "application/excel");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName + ".xlsx");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            OutputStream os = response.getOutputStream();
            book.write(os);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new IOException(e.getMessage());
        }
    }

    /**
     * 获取当前用户信息
     *
     * @return 当前用户信息
     */
    protected UserVo getCurrentUser() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String token = request.getHeader("token");
        if(StringUtil.isEmpty(token)){
            return null;
        }
        JsonResult<UserVo> j = userFeignClient.getUserFromCache(token);
        UserVo u = j.getData().get(0);
        return u;
    }
    
}
